// 异步修改state变量
import * as types from './mutation-type'
import { login, getUserMenuInfoList, LoginOut } from '@/utils/apis'

// 登录
export const set_user = ({commit}, data) => {
    return new Promise((resolve, reject) => {
        login(data).then(res => {
            if (res.errCode == 200) {
                let { userLoginToken, user } = res.data
                localStorage.setItem('userLoginToken', userLoginToken)
                localStorage.setItem('user', JSON.stringify(user))
                commit(types.SET_USER, user)
            } 
            resolve(res)
        })
    })
}

// 获取菜单
export const get_menu = ({commit}) => {
    return new Promise((resolve, reject) => {
        getUserMenuInfoList().then(res => {
            if (res.errCode == 200) {
                let { userRoleMenu } = res.data
                commit(types.GET_MENU_LIST, userRoleMenu)
            }
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

// 登出
export const login_out = ({commit}) => {
    LoginOut().then(res => {
        if (res.errCode == 200) {
            localStorage.removeItem('userLoginToken')
            localStorage.removeItem('user')
            setTimeout(() => {
                location.href = '/login'
            }, 1500);
        }
    }).catch(err => {
        setTimeout(() => {
            location.href = '/login'
        }, 1500);
    })
}

// 菜单折叠
export const is_collapse = ({commit}) => {
    commit(types.IS_COLLAPSE)
}
